package me.zhengjie.modules.system.service.mapstruct.convertor.impl;

import lombok.RequiredArgsConstructor;
import me.zhengjie.config.MappingProperties;
import me.zhengjie.modules.system.domain.Requirement;
import me.zhengjie.modules.system.repository.RequirementRepository;
import me.zhengjie.modules.system.service.mapstruct.convertor.SerialNoConvertor;
import me.zhengjie.utils.StringUtils;
import org.mapstruct.Named;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;

/**
 * RequirementConvertor
 *
 * @author guoyuan
 * @version 1.0.0
 * @since 1.0.0
 */
@Component
@RequiredArgsConstructor
@Named("requirementConvertor")
public class RequirementConvertor implements SerialNoConvertor {

    private static final String SPLIT = "-";
    private final RequirementRepository requirementRepository;
    private final MappingProperties mappingProperties;

    /**
     * 对象转json字符串
     *
     * @param requirementTheme /
     * @return /
     */
    @Named("requirementThemePenetrate")
    public String requirementThemePenetrate(String requirementTheme) {
        return requirementTheme;
    }

    @Named("requirementId2Integer")
    public Integer requirementId2Integer(String requirementId) {
        if (StringUtils.isBlank(requirementId)) {
            return null;
        }
        final int i = requirementId.lastIndexOf(SPLIT) + 1;
        final String strDocNum = requirementId.substring(i);
        return Integer.parseInt(strDocNum);
    }

    @Named("requirementId2String")
    public String requirementId2String(Integer requirementId, Timestamp createTime) {
        final Requirement first = requirementRepository.findFirstByOrderByRequirementIdDesc();
        final Integer zeroLen = mappingProperties.getRequirementNumZeroLen();
        final String docNumTimePattern = mappingProperties.getRequirementNumTimePattern();
        final String part1 = mappingProperties.getRequirementNumPrefix();
        final String part2 = new SimpleDateFormat(docNumTimePattern).format(createTime);
        final String prefix = part1 + SPLIT + part2 + SPLIT;
        String strRequirementId;
        if (first != null) {
            strRequirementId = buildSerialNo(requirementId, prefix, zeroLen, first.getRequirementId());
        } else {
            strRequirementId = prefix + requirementId;
        }
        return strRequirementId;
    }

}
